//
//  RecordDetails.m
//  MUBATE
//
//  Created by sunbin on 2017/2/22.
//  Copyright © 2017年 Quanli. All rights reserved.
//

#import "RecordDetails.h"
#import "RecordDetailsHeaderFooterView.h"
#import "RecentRecordModel.h"


static NSString * RecordDetailsHeaderFooterViewIdentifier = @"RecordDetailsHeaderFooterViewIdentifier";

@interface RecordDetails ()<UITableViewDelegate ,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic ,strong) NSDictionary *data;
@end

@implementation RecordDetails
{
    NSArray *textLabelAry;
}
- (void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
    self.jHUDRect = self.view.frame;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    WEAKSELF;
     [self loadData];
    
//    [weakSelf.hudView setJHUDReloadButtonClickedBlock:^() {
//        [weakSelf loadData];
//        
//    }];
    


    
}

#pragma make 先出现表table 在圆圈一直旋转
- (void)loadData{

    WEAKSELF;
    NSDictionary *parameters = @{@"uid":@([YConfig getOwnID]),
                                 @"sign":SIGN,
                                 @"id":_dataTy==dicTy?IF_NULL_TO_STRING([_msgDic objectForKey:@"id"]):_model.list_id,
                                 @"type":_dataTy==dicTy?IF_NULL_TO_STRING([_msgDic objectForKey:@"type"]):_model.type,
                                 };
    __block BOOL noData;    // yes表示无数据 no表示有数据

    __block NSDictionary *dataDic;
    
    [ZL_NetworkHelper POST:LOGDETAIL parameters:parameters responseCache:^(id responseCache) {
        // 查看是否存在缓存
        NSDictionary *dic = (NSDictionary *)responseCache;
       
        NSInteger count = [(NSDictionary*)responseCache count];
        BOOL isCash = count!=0?YES:NO;
        noData = !isCash;
        
        // 存在缓存数据
        NSString *res = IF_NULL_TO_STRING([dic objectForKey:@"res"]);
        if ([res isEqualToString:@"1"]) {
            
            dataDic = [dic objectForKey:@"data"];
        }else{
            dataDic = nil;
        }
    } success:^(id responseObject) {
        if (noData) {
           //没有缓存获取数据 获取网络数据 相当于第一次获取数据
            NSDictionary *dic = (NSDictionary *)responseObject;
            NSString *res = IF_NULL_TO_STRING([dic objectForKey:@"res"]);
            if ([res isEqualToString:@"1"]) {
                [weakSelf respondData:[dic objectForKey:@"data"] cash:NO response:Succeed];//加载数据
            }else{
                // 此处 没有数据 当有网又没有获取导数据模拟加载 失败
                [weakSelf respondData:nil cash:NO response:Error];

                
            }
        }else{
           //有缓存数据在缓存里已经做处理加载数据
            [weakSelf respondData:dataDic cash:YES response:Succeed];

        }
    } failure:^(NSError *error) {
        if (noData) {
            NSLog(@"无数据 显示jhud 无网络时");
            [weakSelf activityLoadShowFailure:YES response:Failure];

        }else{
        //有缓存数据时
            [weakSelf respondData:dataDic cash:YES response:Failure];

        }
    }];

    
    
    


}


// 数据展示 模拟加载动画 需要看是否已经存在缓存
- (void)respondData:(NSDictionary *)dic cash:(BOOL)iscash response:(responseState)state{
    WEAKSELF;
    _data = dic;
    if (iscash) {
        //1直接刷新
        [weakSelf dataSource];
        [weakSelf.tableView reloadData];

    }else{
        //2无缓存 模拟数据加载
        [weakSelf activityLoadShowFailure:NO response:state];
        
    }
}
- (void)dataSource{
    WEAKSELF;
    textLabelAry = @[@[@"交易金额" ,@"共赏返现" ,@"交易时间" ,@"流水编号" ,@"支付编号"],
                     @[@"返现时间" ,@"流水编号"]];
    [weakSelf initView];
    

}


- (void)activityLoadShowFailure:(BOOL)failure response:(responseState)state{
    WEAKSELF;
    // failure失败 无网络 因此此处failure=Yes就不显示loadingCircleJoinAnimation
    if (failure) {
        [weakSelf loadingFailure:@"无网络" refreshTitle:nil customImage:@"nullData" indicatorViewSize:CGSizeMake(130, 130) showAtView:weakSelf.view];
    }else{
        [self loadingCircleJoinAnimation:@"loadingCircleJoinAnimation" showAtView:self.view];
        [weakSelf dataSource];

        //JHUD消失
  //一直旋转 bug处理 问题处于刷新
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.f * NSEC_PER_SEC)),
                       dispatch_get_main_queue(), ^{
                           for (UIView * view in [self.view subviews]) {
                               if ([view isKindOfClass:[JHUD class]]) {
                                   [view removeFromSuperview];
                               }
                           }
                           if (state == Succeed) {
                               [self.tableView reloadData];

                           }else{
                               [weakSelf loadingFailure:@"数据获取失败" refreshTitle:nil customImage:@"nullData" indicatorViewSize:CGSizeMake(130, 130) showAtView:weakSelf.view];
                           }
        });

    }
    
}




- (void)initView{

    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
  
    [self registerNib];
}

- (void)registerNib{
    [self.tableView registerNib:[UINib nibWithNibName:@"RecordDetailsHeaderFooterView" bundle:nil] forHeaderFooterViewReuseIdentifier:RecordDetailsHeaderFooterViewIdentifier];

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [[textLabelAry objectAtIndex:_ty] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *cellID = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellID];
    }
    cell.textLabel.text = [[textLabelAry objectAtIndex:_ty] objectAtIndex:indexPath.row];
    
    cell.detailTextLabel.text = [[@[
  @[IF_NULL_TO_STRING([_data objectForKey:@"money"]),
      [NHUtils moneyWithInterge:[IF_NULL_TO_STRING([_data objectForKey:@"return_money"]) floatValue]],
      IF_NULL_TO_STRING([_data objectForKey:@"timer"]),
      IF_NULL_TO_STRING([_data objectForKey:@"order"]),
      IF_NULL_TO_STRING([_data objectForKey:@"no"])] ,
  @[IF_NULL_TO_STRING([_data objectForKey:@"timer"]),
    IF_NULL_TO_STRING([_data objectForKey:@"order"])]] objectAtIndex:_ty] objectAtIndex:indexPath.row];

    
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    RecordDetailsHeaderFooterView *head = [tableView dequeueReusableHeaderFooterViewWithIdentifier:RecordDetailsHeaderFooterViewIdentifier];
    head.backgroundView = [[UIImageView alloc] initWithImage:[NHUtils imageWithColor:[UIColor appCellColor] size:CGSizeMake(SCREEN_WIDTH, kscaleHeight(140.f)) alpha:1]];
    
    head.name.text  = _dataTy==dicTy?
    IF_NULL_TO_STRING([_msgDic objectForKey:@"name"]):
    _model.name;
    head.money.text = _dataTy==dicTy?
    [NHUtils moneyWithInterge:[IF_NULL_TO_STRING([_msgDic objectForKey:@"money"]) floatValue]]:
    [NHUtils moneyWithInterge:[_model.affect_money floatValue]];
//    head.stateInfor.text = _dataTy==dicTy?
//    IF_NULL_TO_STRING([_msgDic objectForKey:@"stateInfor"]):
//    _model.status_info;

    return head;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return kscaleHeight(140.f);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];


}






//{
//    "res": "1",
//    "msg": "数据获取成功",
//    "data": {
//        "money": "1.00",
//        "type": "1",
//        "out_mid": "or1EwvxFhG5upMj60FJa",
//        "company": "优衣库",
//        "store": "南山分店",
//        "status": "1",
//        "provice": "广东",
//        "city": "深圳",
//        "area": "南山区",
//        "return_money": "0.1000000",
//        "timer": "2017-02-25 00:51",
//        "order": "P20170225005144281850",
//        "no": "4005112001201702251203879114",
//        "status_info": "交易成功"
//    }
//}

@end
